import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:mall/utils/client/platform.dart';
import 'package:mall/utils/hud/hud_util.dart';
import 'package:photo_manager/photo_manager.dart';

import 'permission_util.dart';

abstract class FileService {
  //真实的保存业务逻辑
  static Future<void> toDoSave(String path, BuildContext context) async {
    var isMobile = UtilPlatform.isAndroid || UtilPlatform.isIOS;
    bool res = isMobile ? await PermissionUtil.photoPermission(context) : true;
    if (res == false) return;

    HUDUtil.show('图片保存中...');
    RegExp regExp = RegExp(
      r'^(http|https):\/\/',
      caseSensitive: false,
    );
    if (regExp.hasMatch(path)) {
      try {
        var response = await Dio().get(path, options: Options(responseType: ResponseType.bytes));
        // 将下载的图片数据保存到临时文件
        if (isMobile) {
          Uint8List bytes = Uint8List.fromList(response.data);
          await _saveImageToAlbum(bytes);
        } else {
          // String base64Str = base64Encode(response.data);
          // HtmlServer.saveImage(base64Str);
          // HUDUtil.dismiss();
          // Future.delayed(const Duration(milliseconds: 100), () {
          //   HUDUtil.toast('图片保存成功');
          // });
        }
      } catch (e) {
        HUDUtil.dismiss();
      }
    } else {
      File file = File(path);
      if (await file.exists()) {
        // 读取文件数据
        List<int> bytes = await file.readAsBytes();
        // 转换为Uint8List
        Uint8List imageData = Uint8List.fromList(bytes);
        final result = await ImageGallerySaver.saveImage(Uint8List.fromList(imageData));
        HUDUtil.dismiss();
        if (result['isSuccess']) {
          HUDUtil.toast('图片保存成功');
        } else {
          HUDUtil.toast('图片保存失败');
        }
      } else {
        HUDUtil.toast('图片保存失败');
      }
    }
  }

  static Future<void> _saveImageToAlbum(Uint8List imagePath) async {
    try {
      // 获取相册管理器
      final timeTag = DateTime.now().microsecondsSinceEpoch;
      final asset = await PhotoManager.editor.saveImage(imagePath, filename: '$timeTag.png');
      HUDUtil.dismiss();
      if (asset != null) {
        HUDUtil.toast('图片保存成功');
      } else {
        HUDUtil.toast('图片保存失败');
      }
    } catch (e) {
      HUDUtil.dismiss();
    }
  }
}
